﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using centraldba_dbrestore_utility.Data;

namespace centraldba_dbrestore_utility
{
    /// <summary>
    /// Interaction logic for StatusWindow.xaml
    /// </summary>
    public partial class StatusWindow : Window
    {
        #region " Constructor "

        SQLRecoveryManager_DB rman;
        string _destinationInstance;

        public StatusWindow()
        {
            InitializeComponent();

            // Initialize the interface to data
            rman = new SQLRecoveryManager_DB();
            rman.InfoMessage += new System.Data.SqlClient.SqlInfoMessageEventHandler(rman_InfoMessage);
            rman.ProcessComplete += new EventHandler(rman_StatementCompleted);
        }

        #endregion

        #region " Events "

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ResizePopupWindow();
        }

        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            ResizePopupWindow();
        }

        private void cmdClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void PopupClose_Click(object sender, RoutedEventArgs e)
        {
            wndResults.Close();
        }

        private void OnResultsClicked(object sender, RoutedEventArgs e)
        {
            wndResults.Show();
        }

        void rman_StatementCompleted(object sender, EventArgs e)
        {
            Dispatcher.BeginInvoke((Action)delegate
            {
                bool execute_next = false;
                bool completed_last_step = true;

                // Find the current executing command
                foreach (MyRestoreScript mrs in dataGrid1.Items)
                {
                    if (execute_next)
                    {
                        // Since there was another step, completed_last_step is false
                        completed_last_step = false;

                        // Execute the first command
                        mrs.Started = true;
                        mrs.Processing = true;
                        rman.ExecuteQuery(_destinationInstance, mrs.Command);
                        break;
                    }

                    // Mark the current step as completed
                    if (mrs.Processing)
                    {
                        mrs.Processing = false;
                        execute_next = true;
                    }
                }

                if (completed_last_step)
                    MessageBox.Show("Restore Operation Complete.", "Database Restore");
            });
        }

        void rman_InfoMessage(object sender, System.Data.SqlClient.SqlInfoMessageEventArgs e)
        {
            Dispatcher.BeginInvoke((Action)delegate
            {
                // Declare Local Variables
                StringBuilder msg = new StringBuilder();
                bool job_failed = false;

                // Get the message(s)
                if (e.Errors.Count > 0)
                {
                    foreach (System.Data.SqlClient.SqlError er in e.Errors)
                    {
                        // Add the message
                        msg.AppendLine(er.Message);

                        // Determine if this is a job failure
                        if (er.Class > 10)
                            job_failed = true;
                    }
                }
                else
                    msg.AppendLine(e.Message);

                // Update the status of the job step
                foreach (MyRestoreScript mrs in dataGrid1.Items)
                {
                    if (mrs.Processing)
                    {
                        // Set status
                        mrs.Succeeded = !job_failed;

                        // Add result message
                        mrs.Result += msg.ToString();

                        // Exit for loop
                        break;
                    }
                }

                // Cleanup
                msg.Clear();
            });
        }

        #endregion

        #region " Methods "

        private void ResizePopupWindow()
        {
            wndResults.Width = this.Width - 50;
            wndResults.Height = this.Height - 50;
        }

        public void RestoreDatabase(string sourceInstance, string destinationInstance, string sourceDatabase, string destinationDatabase, string restoreLabel, Int32 backup_set_id, string stopat_time)
        {
            // Pre-process parameters
            sourceInstance = sourceInstance.Trim();
            destinationInstance = destinationInstance.Trim();
            sourceDatabase = sourceDatabase.Trim();
            destinationDatabase = destinationDatabase.Trim();
            restoreLabel = restoreLabel.Trim();
            stopat_time = stopat_time.Trim();

            // Ensure destinationInstance has been set
            if (destinationInstance.Length.Equals(0))
                destinationInstance = sourceInstance;

            // Ensure destinationDatabase has been set
            if (destinationDatabase.Length.Equals(0))
                destinationDatabase = sourceDatabase;

            // Store the destination instance for future commands
            _destinationInstance = destinationInstance;

            // Remove any previous binding
            dataGrid1.ItemsSource = null;

            // Declare Local Variables
            Collection<MyRestoreScript> restoreScripts;

            // Get the restore script
            restoreScripts = rman.getRestoreScripts(sourceInstance, destinationInstance, sourceDatabase, destinationDatabase, restoreLabel, backup_set_id, stopat_time);

            // Setup the status display
            dataGrid1.ItemsSource = restoreScripts;

            // Perform the restore first script
            MyRestoreScript s = restoreScripts[0];

            // Execute the first command
            s.Started = true;
            s.Processing = true;
            rman.ExecuteQuery(destinationInstance, s.Command);
        }

        #endregion
    }
}
